const exec = require('child_process').exec;
const chalk = require('chalk');
const ora = require('ora');
const spinner = ora();



/**
 * 安装全局http-server
 */
function installServerEslint() {
    return new Promise((resolve, reject)=>{
        exec(`http-server -v`, (error,stdout,stderr) => {
            if (stdout) {
                console.log('\n'+chalk.blue(`全局http-server版本为 ${stdout}`));
                resolve()
            }else{
                spinner.text = chalk.green(`正在全局安装 http-server`);
                exec(`npm install -g http-server`, (error,stdout,stderr) => {
                        if(error){
                            console.log(chalk.red(error));
                            process.exit()
                        }else{
                            resolve()
                        }
                    })
                
            }
        })
    })
}

/**
 * 判断端口号
 */
function checkPortExist(port) {
    return new Promise((resolve, reject)=>{
        exec(`lsof -i:${port}`, (error,stdout,stderr) => {
            if (stdout) {
                console.log(chalk.red(`\n 当前端口号已被占用：\n ${stdout}`));
                resolve(true)
            }else{
                resolve()
            }
        })
    })
}

/**
 * 主入口
 */
async function main(cmd){
    if(!cmd.port){
        console.log(chalk.red(` 请输入端口号 -p `));
        return;
    }
    const PortExist = await checkPortExist(cmd.port);
    if(PortExist) return;
    spinner.start();
    //现在改为 -D 安装，不再需要 -g安装了
    //installServerEslint().then((res)=>{
            var child = exec(`npm run http-server -- ${process.cwd()} -p ${cmd.port}`, {
                cwd: __dirname,
            });
            spinner.succeed(`已启动\n  child.pid: ${child.pid} \n  child.spawnfile: ${child.spawnfile}\n  child.spawnargs: ${child.spawnargs}`);
            child.stdout.on('data',function (data) {
                //主要输出在这里
                console.log(data);
            });
            child.stderr.on('data',function (data) {
                if(data.indexOf('Error: listen EADDRINUSE')>-1){
                    console.log(chalk.red(`  端口号${cmd.port}已被占用`));
                }else{
                    console.log(chalk.red(data));
                }
            });
            child.stdin.on('data',function(data){
                console.log('stdin: ' + data);
            })
            child.on('close',function (code) {
                console.log('child process exited with code ' + code);
            });
    //})
}
module.exports = main;


/* 
方法一： Node 内置模块http的使用
var http = require('http')
http.createServer(function(req, res){
  	res.writeHead(200, { 'Content-Type': 'text-plain' });
  	res.end('Hello World');
}).listen(8083);


方法二：使用 express 的使用
// npm i express -S
const express = require('express')
const app = express()
// public为静态资源路径，默认读取子文件index.html
app.use(express.static('public'))
app.listen(8083, () => {
  console.log('server start!')
})


方法三：使用 http-server 也是最方便的方法
// Step1 全局安装 http-server 
npm install http-server -g 

// Step2 进入目标文件夹启动 http-server 或者指定端口号 http-server -p 3000 
cd dist  http-server 
http-server -p 3000
// Step3 访问 localhost:8080 或者 localhost:3000
 */
